import React, { useEffect, useRef } from 'react';
import {
  Drawer,
  Box,
  Typography,
  TextField,
  Stack,
  Divider,
  IconButton,
  Tooltip
} from '@mui/material';
import { useForm } from 'react-hook-form';
import { zodResolver } from '@hookform/resolvers/zod';
import { z } from 'zod';
import InfoIcon from '@mui/icons-material/Info';
import { useFlowStore } from '../store/flowStore';
import { NodeType, NodeSchemas, type NodeData } from '../types/behaviorTree';

interface PropertiesPanelProps {
  open: boolean;
  onClose: () => void;
  selectedNodeId: string | null;
}

/**
 * @function PropertiesPanel
 * @description 属性编辑面板组件。根据选中的节点显示对应的表单，并实时更新节点数据。
 * @param {PropertiesPanelProps} props - 组件属性，包括是否打开、关闭回调和选中节点ID。
 */
const PropertiesPanel: React.FC<PropertiesPanelProps> = ({ open, onClose, selectedNodeId }) => {
  const selectedNode = useFlowStore((state) => 
    selectedNodeId ? state.nodes.find((node) => node.id === selectedNodeId) : null
  );
  
  const updateNodeData = useFlowStore((state) => state.updateNodeData);

  const schema =
    selectedNode?.type && (selectedNode.type in NodeSchemas)
      ? NodeSchemas[selectedNode.type as keyof typeof NodeSchemas]
      : z.object({ label: z.string() });

  const {
    register,
    handleSubmit,
    reset,
    watch,
    formState: { errors },
  } = useForm<NodeData>({
    resolver: zodResolver(schema),
    values: selectedNode?.data || { label: '' },
  });

  useEffect(() => {
    if (selectedNode) {
      reset(selectedNode.data);
    } else {
      reset({ label: '' });
    }
  }, [selectedNode, reset]);

  const debounceTimeoutRef = useRef<ReturnType<typeof setTimeout> | null>(null);

  useEffect(() => {
    const subscription = watch((value, { name, type }) => {
      if (selectedNodeId && name && type === 'change') {
        if (debounceTimeoutRef.current) {
          clearTimeout(debounceTimeoutRef.current);
        }

        debounceTimeoutRef.current = setTimeout(() => {
          const updatedValue = value[name as keyof NodeData];

          let dataToUpdate: Partial<NodeData>;
          if (name === 'times' && selectedNode?.type === NodeType.Decorator) {
            const numValue = Number(updatedValue);
            dataToUpdate = { [name]: isNaN(numValue) ? undefined : numValue } as Partial<NodeData>;
          } else {
            dataToUpdate = { [name]: updatedValue } as Partial<NodeData>;
          }

          updateNodeData(selectedNodeId, dataToUpdate);
          console.log(`Node ${selectedNodeId} data updated:`, dataToUpdate);
        }, 300);
      }
    });
    
    return () => {
      subscription.unsubscribe();
      if (debounceTimeoutRef.current) {
        clearTimeout(debounceTimeoutRef.current);
      }
    };
  }, [watch, selectedNodeId, updateNodeData, selectedNode?.type]);

  const onSubmit = () => {
    // 可以在这里添加额外的提交逻辑
  };

  if (!open) {
    return null;
  }

  // 获取节点类型描述
  const getNodeDescription = (type: NodeType) => {
    switch (type) {
      case NodeType.Sequence:
        return '序列节点：按顺序执行所有子节点，直到其中一个失败';
      case NodeType.Selector:
        return '选择节点：按顺序执行子节点，直到其中一个成功';
      case NodeType.Action:
        return '动作节点：执行具体的行为动作';
      case NodeType.Condition:
        return '条件节点：判断条件是否满足';
      case NodeType.Decorator:
        return '装饰器节点：修改子节点的行为';
      default:
        return '未知节点类型';
    }
  };

  return (
    <Drawer
      anchor="right"
      open={open}
      onClose={onClose}
      variant="persistent"
      sx={{
        width: 320,
        flexShrink: 0,
        '& .MuiDrawer-paper': {
          width: 320,
          boxSizing: 'border-box',
          position: 'absolute',
          right: 0,
          top: 64,
          height: 'calc(100% - 64px)',
        },
      }}
    >
      <Box sx={{ p: 2 }}>
        <Typography variant="h6" gutterBottom>
          节点属性
        </Typography>
        
        {selectedNode ? (
          <form onSubmit={handleSubmit(onSubmit)}>
            <Stack spacing={2}>
              <Box>
                <Box sx={{ display: 'flex', alignItems: 'center', mb: 1 }}>
                  <Typography variant="subtitle1">
                    类型: {selectedNode.type
                      ? selectedNode.type.charAt(0).toUpperCase() + selectedNode.type.slice(1)
                      : '未知类型'}
                  </Typography>
                  <Tooltip title={getNodeDescription(selectedNode.type as NodeType)}>
                    <IconButton size="small" sx={{ ml: 1 }}>
                      <InfoIcon fontSize="small" />
                    </IconButton>
                  </Tooltip>
                </Box>
                
                <Typography variant="body2" color="text.secondary" sx={{ mb: 2 }}>
                  {getNodeDescription(selectedNode.type as NodeType)}
                </Typography>
              </Box>
              
              <Divider />
              
              <TextField
                label="标签"
                {...register('label')}
                error={!!errors.label}
                helperText={errors.label?.message || '节点的显示名称'}
                fullWidth
                margin="normal"
              />

              {selectedNode.type === NodeType.Action && (
                <TextField
                  label="动作名称"
                  {...register('actionName')}
                  error={!!errors.actionName}
                  helperText={errors.actionName?.message || '指定要执行的动作'}
                  fullWidth
                  margin="normal"
                />
              )}

              {selectedNode.type === NodeType.Condition && (
                <TextField
                  label="条件"
                  {...register('condition')}
                  error={!!errors.condition}
                  helperText={errors.condition?.message || '定义判断条件'}
                  fullWidth
                  margin="normal"
                />
              )}

              {selectedNode.type === NodeType.Decorator && (
                <TextField
                  label="重复次数"
                  type="number"
                  {...register('times', { valueAsNumber: true })}
                  error={!!errors.times}
                  helperText={errors.times?.message || '装饰器重复执行的次数'}
                  fullWidth
                  margin="normal"
                />
              )}
            </Stack>
          </form>
        ) : (
          <Box sx={{ mt: 2 }}>
            <Typography>请选择一个节点以编辑其属性。</Typography>
            <Typography variant="body2" color="text.secondary" sx={{ mt: 2 }}>
              提示：点击画布中的任意节点即可选中并编辑其属性。
            </Typography>
          </Box>
        )}
      </Box>
    </Drawer>
  );
};

export default PropertiesPanel;